package cn.micro.request.log.filters;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;

/**
 * 自定义 HttpServletResponseWrapper
 *
 * @see HttpServletResponseWrapper
 */
class RequestCachingResponseWrapper extends org.springframework.web.util.ContentCachingResponseWrapper {

    private int status = 200;

    private final boolean alwaysOk;

    /**
     * Create a new ContentCachingResponseWrapper for the given servlet response.
     *
     * @param response the original servlet response
     */
    public RequestCachingResponseWrapper(HttpServletResponse response, boolean alwaysNotFound) {
        super(response);
        this.alwaysOk = alwaysNotFound;
    }

    @Override
    public int getStatus() {
        if (alwaysOk) {
            return 200;
        }
        return super.getStatus();
    }

    public int getLocalStatus() {
        return this.status;
    }

    @Override
    public void setStatus(int sc) {
        this.status = sc;
        if (!alwaysOk) {
            super.setStatus(sc);
        }
    }

    @Override
    public void sendError(int sc)
            throws IOException {
        sendError(sc, "处理异常");
    }

    @Override
    public void sendError(int sc, String msg) throws IOException {
        copyBodyToResponse(false);
        if (isCommitted()) {
            throw new IllegalStateException(msg);
        }
        this.status = sc;
        if (!this.alwaysOk) {
            super.sendError(sc, msg);
        }
    }

}
